<template>
  <div class="g-page-container">
    <PageHeader title="M+3预测" />
    <div class="g-content-container">
      <SearchForm
        ref="search-form"
        :page-type="pageType"
        @search="handleSearch"
      />
      <ButtonGroup :options="buttons" @click="handleButtonClick" />
      <TableList
        :scroll="{ x: '100%', y: 'calc(100vh - 400px)' }"
        :pagination="paginationMixin"
        :loading="loading"
        :data-source="dataSource"
        :page-type="pageType"
        :row-selection="rowSelectionMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>

    <component
      :is="currentComponent"
      :visible.sync="visibleDrawer"
      :current-node="currentNode"
      :detail="detail"
      :plan-id="planId"
      :page-type="pageType"
      @fresh="getList"
    />
    <DialogTransferAdminForecast
      :visible.sync="visibleModal"
      :plan-id="planId"
      :selecteds="selectedInfos"
      number="M+9编号"
      @fresh="getList"
    />
  </div>
</template>
<script>
import ButtonGroup from '@/components/button/ButtonGroup.vue';
import mixinTable from '@/mixins/mixin-table.js';
import {
  getMforecastDetail,
  postDeleteMforecast,
  postLoadTableList,
} from '@/api/forecast.js';

import SearchForm from './components/SearchForm.vue';
import TableList from './components/TableList.vue';
import DialogTransferAdminForecast from '@/components/dialog/DialogTransferAdminForecast.vue';
import {
  FORECAST_NODE_THREE as PAGE_NODE,
  FORECAST_TYPE as PAGE_TYPE,
} from '@/constants/index';

import DrawerStart from './components/DrawerStart.vue';
import DrawerGroupRecord from './components/DrawerGroupRecord.vue';
import DrawerSalerAuditFirst from './components/DrawerSalerAuditFirst.vue';
import DrawerEmitePreAllot from './components/DrawerEmitePreAllot.vue';
import DrawerGroupEmiteTotal from './components/DrawerGroupEmiteTotal.vue';
import DrawerGroupAuditSecondary from './components/DrawerGroupAuditSecondary.vue';
import DrawerSalerAuditSecondary from './components/DrawerSalerAuditSecondary.vue';
import DrawerEnd from './components/DrawerEnd.vue';
import moment from 'moment';

export default {
  components: {
    ButtonGroup,
    SearchForm,
    TableList,
    DialogTransferAdminForecast,
    DrawerStart,
    DrawerGroupRecord,
    DrawerSalerAuditFirst,
    DrawerEmitePreAllot,
    DrawerGroupEmiteTotal,
    DrawerGroupAuditSecondary,
    DrawerSalerAuditSecondary,
    DrawerEnd,
  },
  mixins: [mixinTable],
  props: {
    pageType: {
      type: String,
      default: 'M3',
    },
  },
  data() {
    return {
      selectedInfos: [],
      columnKey: '',
      visibleModal: false,
      visibleAdd: false,
      visibleDrawer: false,
      currentComponent: 'DrawerStart',
      detail: {},
      planId: undefined,
      asc: true,
      currentNode: PAGE_NODE[1],
    };
  },

  computed: {
    buttons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          type: 'primary',
          label: `发起${PAGE_TYPE[this.pageType]}预测`,
          icon: 'plus',
          authKey: `${this.pageType}-button-launch`,
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
          authKey: `${this.pageType}-button-delete`,
          disabled,
        },
        {
          key: 'retweet',
          label: '转他人处理',
          icon: 'retweet',
          authKey: `${this.pageType}-button-transfer`,

          disabled,
        },
      ];
    },
    searchForm() {
      return this.$refs['search-form']?.form || {};
    },
  },
  watch: {
    visibleModal: {
      handler(val) {
        if (!val) {
          this.rowSelectionMixin.selectedRowKeys = [];
        }
      },
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (to.query?.id) {
        vm.handleNumberClick(to.query);
      }
    });
  },
  created() {
    this.getList();
  },
  methods: {
    async getMforecastDetail(id) {
      const result = await getMforecastDetail(id);
      this.detail = result?.data.data;
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.form || {};
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
        ...form,
        startTime:
          form.startTime &&
          moment(form.startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime:
          form.endTime && moment(form.endTime).format('YYYY-MM-DD HH:mm:ss'),
      };
      return { ...page, type: this.pageType };
    },
    handleSearch() {
      this.paginationMixin.current = 1;
      this.getList();
    },
    async getList() {
      const form = this.getSearchForm();
      this.loading = true;
      const result = await postLoadTableList(form).finally(
        () => (this.loading = false)
      );
      this.paginationMixin.total = result?.data?.data?.total;
      this.dataSource = result?.data?.data?.records;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    async retweetCallback() {
      console.log(
        'this.rowSelectionMixin.selectedRows: ',
        this.rowSelectionMixin.selectedRows
      );
      const selectedInfos = this.rowSelectionMixin.selectedRows
        .filter((item) => item.currStatus === '2')
        .map((item, i) => {
          return {
            serialNumber: item.serialNumber || '',
            currentUserId: item.handleUserId || '',
            planId: item.id,
          };
        });
      if (!selectedInfos.length) {
        this.$message.info(
          `仅可转审批中的数据，现有 ${selectedInfos.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可转审批中的数据，共 ${selectedInfos.length} 条，是否确认？`
        );

        this.visibleModal = true;
        this.selectedInfos = selectedInfos;
      } catch (error) {
        // console.log('error: ', error);
      }
    },
    addCallback() {
      this.currentComponent = 'DrawerStart';
      this.currentNode = PAGE_NODE[1];
      this.planId = undefined;
      this.detail = {};
      this.visibleDrawer = true;
    },

    async deleteCallback() {
      const selectedRowKeys = this.rowSelectionMixin.selectedRowKeys || [];
      const checkedRows = this.dataSource.reduce((pre, cur) => {
        if (selectedRowKeys.includes(cur.id)) {
          pre.push(cur);
        }
        return pre;
      }, []);
      const ids = checkedRows
        .filter((item) => item.currStatus === '1')
        .map((item) => item.id);
      if (!ids.length) {
        this.$message.info(`仅可删除草稿状态的数据，现有 ${ids.length} 条！`);
        return;
      }
      try {
        await this.$confirm(
          `仅可删除草稿状态的数据，共 ${ids.length} 条，是否确认？`
        );

        await postDeleteMforecast(ids);
        this.$message.success('删除成功');
        this.rowSelectionMixin.selectedRowKeys = [];
        this.getList();
      } catch (error) {
        //
        // console.log('error: ', error);
      }
    },

    async handleNumberClick(record) {
      this.currentNode = PAGE_NODE[Number(record.nodeCode)];
      if (!this.currentNode) {
        this.$message.error('非有效节点，无法进入！');
        return;
      }
      this.currentComponent = `Drawer${this.currentNode.key}`;
      await this.getMforecastDetail(record.id);
      this.planId = record.id;
      this.visibleDrawer = true;
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.getList();
    },
  },
};
</script>

<style lang="less" scoped>
.table-container {
  padding: 10px 20px;
  height: calc(100vh - 160px);
  box-sizing: border-box;
}
</style>
